import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

// 封装邮件发送为Promise
const sendEmailAsync = (transporter, mailOptions) => {
    return new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) reject(error);
            else resolve(info);
        });
    });
};

export async function POST(request) {
    try {
        // 验证请求格式
        if (!request.headers.get('Content-Type')?.includes('application/json')) {
            return NextResponse.json({
                message: "请求需为 JSON 格式",
                success: false
            }, { status: 400 });
        }

        const { to, subject, content } = await request.json();

        // 验证参数
        if (!to || !subject || !content) {
            return NextResponse.json({
                message: "收件人、主题和内容均为必填项",
                success: false
            }, { status: 400 });
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(to)) {
            return NextResponse.json({
                message: "请输入有效的收件人邮箱",
                success: false
            }, { status: 400 });
        }

        // 配置邮件 transporter（使用环境变量存储敏感信息）
        const transporter = nodemailer.createTransport({
            host: "smtp.qq.com",
            port: 465,
            secure: true, // 465端口需开启SSL
            auth: {
                user: process.env.SMTP_USER || "1690544550@qq.com", // 发件人邮箱
                pass: process.env.SMTP_PASS || "znxogkkkexpbeeaj" // QQ邮箱授权码
            },
            pool: true, // 启用连接池提高性能
            tls: {
                rejectUnauthorized: false // 避免本地开发时的证书问题
            }
        });

        // 发送邮件
        await sendEmailAsync(transporter, {
            from: `"网站管理员" <${process.env.SMTP_USER || "1690544550@qq.com"}>`,
            to,
            subject,
            text: content, // 纯文本内容
            html: `<div style="font-family: Arial, sans-serif; line-height: 1.6;">
                    <p>${content.replace(/\n/g, '<br>')}</p>
                    <p style="margin-top: 1.5rem; color: #666;">此邮件为自动回复，请勿直接回复</p>
                  </div>` // HTML格式内容（支持换行）
        });

        return NextResponse.json({
            success: true,
            message: "邮件发送成功"
        });

    } catch (error) {
        console.error("邮件发送失败:", error);
        return NextResponse.json({
            success: false,
            message: `发送失败: ${error.message || '未知错误'}`
        }, { status: 500 });
    }
}